import os
import pathlib
import sys
from urllib.parse import quote_plus

from aop.aop_config import load_global_config


@load_global_config('../config/config.json5')
def gen_model(env='dev'):
    from config.config import CONFIG
    host = CONFIG.get(env)['mysql']['host']
    port = CONFIG.get(env)['mysql']['port']
    username = CONFIG.get(env)['mysql']['username']
    password = quote_plus(CONFIG.get(env)['mysql']['password'])
    database_name = CONFIG.get(env)['mysql']['database']
    profile = CONFIG.get(env)['model_file_suffix']
    print('host', host)
    table_names = CONFIG.get(env)['mysql']['tables']
    if table_names:
        tables = ",".join(table_names)
        print('tables', tables)
        db_uri = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database_name} --tables {tables}'
    else:
        db_uri = f'mysql+pymysql://{username}:{password}@{host}:{port}/{database_name}'

    # 自动生成models
    out_path = pathlib.Path(os.path.abspath(__file__)).parent.parent.joinpath('models') / f'models_{profile}.py'
    print('out_path', out_path)
    os.system(f'sqlacodegen {db_uri} > {out_path}')
    print(f'生成完成 {out_path}')


if __name__ == '__main__':
    if len(sys.argv) > 1:
        env = sys.argv[1]
    else:
        env = 'dev'  # 默认值
    gen_model(env)